package cn.hd.authorService.utils;

import cn.hd.authorService.vo.LoginUser;
import cn.hd.commonService.entity.SysUser;
import cn.hd.commonService.exception.CustomException;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class HttpRequestUtils {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HttpServletRequest request;

    /**
     * 获取当前登录用户
     * @return
     * @throws Exception
     */
    public LoginUser getLoginUser() {
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
           throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"请登录");
        }
        String userId = "";
        try {
            //根据token获取用户id
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        }catch (Exception e){
            throw new CustomException("用户认证失败，请登录");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (loginUser==null){
            throw new CustomException(HttpStatus.UNAUTHORIZED.value(),"请登录");
        }
        return loginUser;
    }
    public SysUser getUser()  {
      return this.getLoginUser().getUser();
    }

    /**
     * 获取当前登录用户id
     * @return
     * @throws Exception
     */
    public String getUserId()  {
        return String.valueOf(this.getLoginUser().getUser().getRecordId());
    }

}
